#include "capturer_video_source.hpp"

#include <algorithm>

#include "api/scoped_refptr.h"
#include "api/video/i420_buffer.h"
#include "api/video/video_frame_buffer.h"
#include "api/video/video_rotation.h"

namespace p2pms
{

CapturerVideoSource::~CapturerVideoSource() = default;

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void CapturerVideoSource::OnOutputFormatRequest(int width, int height,
	const absl::optional<int>& max_fps) 
{
	absl::optional<std::pair<int, int>> target_aspect_ratio = std::make_pair(width, height);
	absl::optional<int> max_pixel_count = width * height;
	m_video_adapter.OnOutputFormatRequest(target_aspect_ratio, max_pixel_count, max_fps);
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void CapturerVideoSource::OnFrame(const webrtc::VideoFrame& original_frame) 
{
	int cropped_width = 0;
	int cropped_height = 0;
	int out_width = 0;
	int out_height = 0;

	webrtc::VideoFrame frame = MaybePreprocess(original_frame);

	bool enable_adaptation;
	{
		webrtc::MutexLock lock(&m_lock);
		enable_adaptation = m_enable_adaptation;
	}

	if (!enable_adaptation) {
		m_broadcaster.OnFrame(frame);
		return;
	}

	if (!m_video_adapter.AdaptFrameResolution(
		frame.width(), frame.height(), frame.timestamp_us() * 1000,
		&cropped_width, &cropped_height, &out_width, &out_height)) {
		// Drop frame in order to respect frame rate constraint.
		return;
	}

	if (out_height != frame.height() || out_width != frame.width()) {
		// Video adapter has requested a down-scale. Allocate a new buffer and
		// return scaled version.
		// For simplicity, only scale here without cropping.
		rtc::scoped_refptr<webrtc::I420Buffer> scaled_buffer =
			webrtc::I420Buffer::Create(out_width, out_height);
		scaled_buffer->ScaleFrom(*frame.video_frame_buffer()->ToI420());
		webrtc::VideoFrame::Builder new_frame_builder =
			webrtc::VideoFrame::Builder()
				.set_video_frame_buffer(scaled_buffer)
				.set_rotation(webrtc::kVideoRotation_0)
				.set_timestamp_us(frame.timestamp_us())
				.set_id(frame.id());
		if (frame.has_update_rect()) {
			webrtc::VideoFrame::UpdateRect new_rect = frame.update_rect().ScaleWithFrame(
				frame.width(), frame.height(), 0, 0, frame.width(), frame.height(),
				out_width, out_height);
			new_frame_builder.set_update_rect(new_rect);
		}
		m_broadcaster.OnFrame(new_frame_builder.build());

	} else {
		// No adaptations needed, just return the frame as is.
		m_broadcaster.OnFrame(frame);
	}
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
rtc::VideoSinkWants CapturerVideoSource::GetSinkWants() 
{
	return m_broadcaster.wants();
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void CapturerVideoSource::AddOrUpdateSink(rtc::VideoSinkInterface<webrtc::VideoFrame>* sink,
  const rtc::VideoSinkWants& wants) 
{
	m_broadcaster.AddOrUpdateSink(sink, wants);
	UpdateVideoAdapter();
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void CapturerVideoSource::RemoveSink(rtc::VideoSinkInterface<webrtc::VideoFrame>* sink)
{
	m_broadcaster.RemoveSink(sink);
	UpdateVideoAdapter();
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void CapturerVideoSource::UpdateVideoAdapter() 
{
	m_video_adapter.OnSinkWants(m_broadcaster.wants());
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
webrtc::VideoFrame CapturerVideoSource::MaybePreprocess(const webrtc::VideoFrame& frame)
{
	webrtc::MutexLock lock(&m_lock);
	if (preprocessor_ != nullptr) {
		return preprocessor_->Preprocess(frame);
	} else {
		return frame;
	}
}

}  // namespace p2pms
